<template>
  <view class="container">
    <!-- 地图组件 -->
    <map 
      class="full-map"
      :latitude="centerLatitude"
      :longitude="centerLongitude"
      :polyline="fencePolyline"
      :markers="markers"
      :scale="scale"
      show-location
      @markertap="onMarkerTap"
      @regionchange="onRegionChange"
    />
    <!-- 手动点名按钮，根据showButton控制显示 -->
    <view v-if="showButton" class="manual-roll-call-button" @click="manualRollCall">
      手动点名
    </view>
    <!-- 底部面板（统计信息），根据showStatsPanel控制显示 -->
    <view v-if="showStatsPanel" class="bottom-panel">
      <view class="bottom-stats-panel">
        <view class="stats-row">
          <view class="stats-item">
            <text class="stats-number" :style="{color: '#4CAF50'}">{{ inFenceCount }}头</text>
            <text class="stats-label">栏内</text>
          </view>
          <view class="stats-item">
            <text class="stats-number" :style="{color: '#FF9800'}">{{ outFenceCount }}头</text>
            <text class="stats-label">栏外</text>
          </view>
        </view>
        <view class="divider"></view>
        <view class="stats-details">
          <view class="detail-item">
            <image :src="areaIcon" class="detail-icon"></image>
            <text>面积：{{ fenceArea }}㎡</text>
          </view>
          <view class="detail-item">
            <image :src="perimeterIcon" class="detail-icon"></image>
            <text>周长：{{ fencePerimeter }}m</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted, nextTick } from 'vue'
import { map } from '@/api/map' 
import areaIcon from '@/static/map/area.png'
import cattleIcon from '@/static/map/bj.png'
import fencePointIcon from '@/static/map/seat.png'
import perimeterIcon from '@/static/map/p.png'

export default {
  setup() {
    // 地图状态
    const centerLatitude = ref(26.340437)
    const centerLongitude = ref(108.019241)
    const scale = ref(16)
    // 数据存储
    const fenceInfo = ref([])
    const numInfo = ref([])
    const locationInfo = ref([])
    // 控制按钮显示
    const showButton = ref(false)
    // 控制统计信息面板显示
    const showStatsPanel = ref(true)
    // 计算围栏路径
    const fencePaths = computed(() => {
      if (fenceInfo.value.length > 0 && fenceInfo.value[0].F_Map) {
        try {
          return JSON.parse(fenceInfo.value[0].F_Map).paths || []
        } catch (e) {
          console.error('解析围栏数据失败:', e)
          return []
        }
      }
      return []
    })
    // 围栏多边形线（增加填充区域，调整颜色）
    const fencePolyline = computed(() => {
      if (fencePaths.value.length > 0) {
        return [{
          points: fencePaths.value.map(p => ({
            latitude: p.lat,
            longitude: p.lng
          })),
          color: "#4CAF50", // 绿色边框
          width: 3,
          dottedLine: false,
          zIndex: 1,
          fillColor: "#C0FFC0", // 淡绿色填充
          borderColor: "#4CAF50" 
        }]
      }
      return []
    })
    // 标记点（围栏点和牛）
    const markers = computed(() => {
      const markers = []
      // 添加围栏点标记（确保图标居中）
      fencePaths.value.forEach((point, index) => {
        markers.push({
          id: `fence-point-${index}`,
          latitude: point.lat,
          longitude: point.lng,
          iconPath: fencePointIcon,
          width: 24, 
          height: 24,
          zIndex: 2,
          anchor: [0.5, 0.5], 
          rotate: 0, 
          alpha: 1.0 
        })
      })
      // 添加牛的标记
      locationInfo.value.forEach((cattle, index) => {
        const lng = parseFloat(cattle.lng) || 0
        const lat = parseFloat(cattle.lat) || 0
        
        markers.push({
          id: `cattle-${index}`,
          latitude: lat,
          longitude: lng,
          iconPath: cattleIcon,
          width: 30,
          height: 30,
          zIndex: 3,
          // 移除callout，只显示图标
          // 若想区分栏内栏外颜色，可在此处根据F_Isster设置iconPath为不同颜色的图标
        })
      })
      // 添加模拟动物标记（只显示图标）
      const addSimulatedAnimals = (center) => {
        if (fencePaths.value.length < 3) return
        
        const minLng = Math.min(...fencePaths.value.map(p => p.lng))
        const maxLng = Math.max(...fencePaths.value.map(p => p.lng))
        const minLat = Math.min(...fencePaths.value.map(p => p.lat))
        const maxLat = Math.max(...fencePaths.value.map(p => p.lat))
        
        const outsideLng = minLng - 0.0005
        const outsideLat = minLat - 0.0005
        
        markers.push({
          id: 'Sim-Inside-Animal',
          latitude: center.lat,
          longitude: center.lng,
          iconPath: cattleIcon,
          width: 30,
          height: 30,
          zIndex: 3
        })
        markers.push({
          id: 'Sim-Outside-Animal',
          latitude: outsideLat,
          longitude: outsideLng,
          iconPath: cattleIcon,
          width: 30,
          height: 30,
          zIndex: 3
        })
      }
      
      if (fencePaths.value.length > 0) {
        const center = {
          lat: (Math.min(...fencePaths.value.map(p => p.lat)) + Math.max(...fencePaths.value.map(p => p.lat))) / 2,
          lng: (Math.min(...fencePaths.value.map(p => p.lng)) + Math.max(...fencePaths.value.map(p => p.lng))) / 2
        }
        addSimulatedAnimals(center)
      }
      
      return markers
    })
    // 围栏统计信息
    const fenceArea = computed(() => {
      return numInfo.value.length > 0? numInfo.value[0].F_Area || 0 : 0
    })
    
    const fencePerimeter = computed(() => {
      return numInfo.value.length > 0? numInfo.value[0].F_Zc || 0 : 0
    })
    
    // 牛的统计信息
    const inFenceCount = computed(() => {
      return locationInfo.value.filter(c => c.F_Isster === 1).length
    })
    
    const outFenceCount = computed(() => {
      return locationInfo.value.filter(c => c.F_Isster === 0).length
    })
    
    // 处理后的牛列表（简化，仅用于数据存储）
    const processedCattleList = computed(() => {
      return locationInfo.value.map(cattle => ({
        id: cattle.F_IMEI || '未知',
        lng: parseFloat(cattle.lng) || 0,
        lat: parseFloat(cattle.lat) || 0,
        inFence: cattle.F_Isster === 1,
        rawData: cattle
      }))
    })
    
    // 判断点是否在围栏内（使用射线法算法）
    const determineIfInFence = (lng, lat) => {
      if (fencePaths.value.length < 3) return false
      
      let inside = false
      const polygon = fencePaths.value
      const length = polygon.length
      
      for (let i = 0, j = length - 1; i < length; j = i++) {
        const xi = polygon[i].lng, yi = polygon[i].lat
        const xj = polygon[j].lng, yj = polygon[j].lat
        
        const intersect = ((yi > lat) !== (yj > lat)) &&
          (lng < (xj - xi) * (lat - yi) / (yj - yi) + xi)
        
        if (intersect) inside = !inside
      }
      
      return inside
    }
    
    // 地图区域变化事件
    const onRegionChange = (e) => {
      if (e.type === 'end') {
        // 可处理地图移动结束后的逻辑
      }
    }
    
    // 标记点点击事件
    const onMarkerTap = (e) => {
      const markerId = e.detail.markerId
      // 这里假设以cattle-开头的是动物标记，你可以根据实际情况调整判断逻辑
      if (markerId && markerId.startsWith('cattle-')) {
        showButton.value = true
        showStatsPanel.value = false
        // 使用nextTick确保DOM更新后再进行后续操作（如果有需要）
        nextTick(() => {
          console.log('按钮已显示，底部信息已隐藏')
        })
      }
    }
    
    // 获取数据
    const fetchData = async () => {
      try {
        const res = await map()
        
        if (res.code === 200) {
          fenceInfo.value = res.data.fenceInfo || []
          numInfo.value = res.data.NumInfo || []
          locationInfo.value = res.data.locationInfo || []
          
          if (fencePaths.value.length > 0) {
            const center = {
              lat: (Math.min(...fencePaths.value.map(p => p.lat)) + Math.max(...fencePaths.value.map(p => p.lat))) / 2,
              lng: (Math.min(...fencePaths.value.map(p => p.lng)) + Math.max(...fencePaths.value.map(p => p.lng))) / 2
            }
            centerLatitude.value = center.lat
            centerLongitude.value = center.lng
          }
        } else {
          uni.showToast({
            title: res.msg || '获取数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
      console.error('获取数据出错:', error)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      }
    }
    // 手动点名方法
    const manualRollCall = () => {
      // 这里可以添加手动点名的具体逻辑
      console.log('手动点名操作')
    }
    onMounted(() => {
      fetchData()
    })
    
    return {
      centerLatitude,
      centerLongitude,
      scale,
      fencePolyline,
      markers,
      fenceArea,
      fencePerimeter,
      inFenceCount,
      outFenceCount,
      processedCattleList,
      areaIcon,
      perimeterIcon,
      fencePointIcon,
      cattleIcon,
      showButton,
      showStatsPanel,
      manualRollCall,
      onMarkerTap
    }
  }
}
</script>

<style>
.container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.full-map {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

.bottom-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  pointer-events: none;
}

.bottom-stats-panel {
  margin: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  padding: 15px;
  z-index: 10;
  width: 90%;
  align-self: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  pointer-events: auto;
}

.stats-row {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stats-number {
  font-size: 20px;
  font-weight: bold;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.divider {
  height: 1px;
  background-color: #eee;
  margin: 10px 0;
}

.stats-details {
  display: flex;
  justify-content: space-around;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}
/* 手动点名按钮样式 */
.manual-roll-call-button {
  position: fixed;
  bottom: 50px;
  left: 50%;
  transform: translateX(-50%);
  background-color: green;
  color: white;
  width: 120px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
</style>